package com.wealth.sms.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wealth.sms.entity.MessageChannel;
import com.wealth.sms.entity.MessageRecord;
import com.wealth.sms.enums.MessageTemplateEnum;
import com.wealth.sms.repository.MessageChannelDao;
import com.wealth.sms.repository.MessageRecordDao;
import com.wealth.sms.repository.MessageTemplateDao;
import com.wealth.sms.service.IMessageChannelService;
import com.wealth.sms.service.IMessageRecordService;

import iaas.enums.StatusEnum;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.ResultObject;

/**
 * 
 * @author chan
 */
@SuppressWarnings(value="all")
@Component
public class MessageChannelServiceImpl extends BaseServiceImpl<MessageChannel> implements IMessageChannelService {

	Logger logger = Logger.getLogger(MessageChannelServiceImpl.class);
	
	@Autowired
	private MessageChannelDao messageChannelDao;
	@Autowired
	private MessageRecordDao messageRecordDao;
	@Autowired
	private MessageTemplateDao messageTemplateDao;
	
	@Autowired
	private IMessageRecordService messageRecordService;

	/** 查询当前企业的短信通道 */
	@Override
	public MessageChannel findMessageChannelByCorpId(Long corpid) throws Exception {
		return messageChannelDao.findByCorpId(corpid);
	}

	/**
	 * 功能：短信请求
	 * create by chan on 2016-08-16
	 * @param corpid  		    	企业id
	 * @param templateTypeId	短信模板类型
	 * @param action		        	动作
	 * @param mobile		    	手机号码
	 * @param map					短信模板参数
	 * @return
	 */
	@Override
	public ResultObject request(Long corpid, Integer templateTypeId, String action, String mobile, Map map) throws Exception {
	
			/** -------- 判断短信通道情况  --------*/
			MessageChannel channel = findMessageChannelByCorpId(corpid); 
			if(channel.getStatus()==StatusEnum.STOP.getValue()){
				return new ResultObject("300", "短信通道已停用",map.get("code"));
			}
			//注册验证码时限制
			if(templateTypeId==MessageTemplateEnum.VERIFYCODE.getValue()){
				boolean isMinimumInterval = messageRecordService.isMinimumInterval(corpid, mobile);
				if(isMinimumInterval){
					return new ResultObject("301", "发送短信过于频繁",null);
				}
				boolean isReachWaringLine = messageRecordService.isReachWaringLine(corpid);
				if(isReachWaringLine){
					return new ResultObject("302", "超出日均最大短信数量",null);
				}
			}
			
			/** -------- 组织参数  --------*/
			String url = channel.getUrl();
			String userid = channel.getUserid();
			String account = channel.getAccount();
			String password = channel.getPassword();
			String extno = channel.getExtno();
			//根据短信类型，查询出短信模板
			String templateContent = messageTemplateDao.findByCorpIdAndType(corpid,templateTypeId).getContent();
			StringBuffer cnt = new StringBuffer();
			//根据短信模板，生成对应的短信记录
			cnt.append("【").append(channel.getSign()).append("】").append(replaceTemplate(templateContent, map));

			/** -------- 使用Httpclient发送请求参数 --------*/
			HttpClient client = new HttpClient();
			PostMethod post = new PostMethod(url);
			try {	
				
				/*-------- 设置请求接口和参数 -------- */
				post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
				NameValuePair[] data = {
						new NameValuePair("action", action),
						new NameValuePair("userid", userid),
						new NameValuePair("account", account),
						new NameValuePair("password", password),
						new NameValuePair("mobile", mobile),
						new NameValuePair("content", cnt.toString()),
						new NameValuePair("extno", extno) 
				};
				post.setRequestBody(data);
				
				/* -------- 发送请求 -------- **/
				client.executeMethod(post);

				/* -------- 返回状态 -------- **/
				// 返回状态
				int statusCode = post.getStatusCode();
				System.out.println("statusCode:" + statusCode);

				// 返回头信息
//				Header[] headers = post.getResponseHeaders();
//				for (Header h : headers) {
//					System.out.println(h.toString());
//				}

				/** -------- 处理结果--------*/
				// 返回信息 {"smsid":"9EF0A9EC94139CDC57F812D0CFB314DA","code":"0"} 表示成功
				//xml string->map
				String result = new String(post.getResponseBody(),"UTF-8");
				System.out.println(result);
				Map<String,String> xmlobj = parseXml(result);
				String returnstatus = xmlobj.get("returnstatus");
				String message = xmlobj.get("message");
				String remainpoint = xmlobj.get("remainpoint");

				
				if (!returnstatus.equals("Success")){
					return new ResultObject("500", "短信http通讯错误", null);
				}
				if(!message.equals("ok")){
					return new ResultObject("500", "短信接口错误 ："+message, null);
				}
				
				//新增短信记录
				MessageRecord record = new MessageRecord(mobile, cnt.toString());
				record.setCorp(channel.getCorp());
				record.setCreateTime(new Date());
				record.setReturnstatus(returnstatus);
				record.setMessage(message);
				messageRecordDao.save(record);
				//修改短信通道剩余条数
				channel.setRemainpoint(Integer.parseInt(remainpoint));
				messageChannelDao.save(channel);
				
				return new ResultObject("000", "短信发送成功,注意查收", null);
				
			} catch (Exception e) {
				logger.error("短信接口错误", e);
				return new ResultObject("999", "短信接口错误", null);
			} finally {
				// 释放链接
				post.releaseConnection();
			}
	}
	
	
	
	
	/** 短信接口发送 */
	@Override
	public ResultObject send(Long corpid,Integer templateTypeId,String mobile,Map map) throws Exception{
		return request(corpid, templateTypeId, "send", mobile, map);
	}
	
	
	public static Map<String,String> parseXml(String text) throws Exception{
		
		Map<String,String> map = new HashMap<String, String>();
		
		Document document = DocumentHelper.parseText(text);
		//得到xml根元素
		Element root = document.getRootElement();
		List<Element> elements = root.elements();
		for (Element element : elements) {
			map.put(element.getName(), element.getText());
		}
		return map;
	}
	
	public static String generateString(String str,List<Object> list){
	      StringBuilder sb  = new StringBuilder();
	      int i=0;
	      for(String temp : str.split("_")){
	          sb.append(temp);
	          if(i<list.size())
	              sb.append(list.get(i));
	          	  i++;
	      }
	      return sb.toString();
	}
	
	public static String replaceTemplate(String template,Map<String,String> map){
		for (String key:map.keySet()) {
			System.out.println("#"+key+"#");
			template = template.replace("#"+key+"#", String.valueOf(map.get(key)));
		}
		return template;
	}
	
	public static Double formatString(String str){
		Double db = Double.valueOf(str);
		db=((int)(db*100))/100.0;
	    return db;
	}
	
	
	public static void main(String[] args) {
		Map<String,String> map = new HashMap<String, String>();
		map.put("code1", "aaa");
		map.put("code2", "bbb");
		String template= "#code1#,wcnm,#code2#";
		template = replaceTemplate(template, map);
		System.out.println(template);
	}
	
//	public static void main(String[] args) {
//		//String result = "{\"smsid\":\"9EF0A9EC94139CDC57F812D0CFB314DA\",\"code\":\"0\"}";
//		String result = "{\"code\":\"-1000\"}";
//		JSONObject jsonobj = JSON.parseObject(result);
//		int code = jsonobj.getInteger("code");
//		String smsid = jsonobj.getString("smsid");
//		System.out.println(code);
//		System.out.println(smsid==null);
//		
//		String str = "尊敬的客户，您的账户_于_年_月_日成功充值，人民币_元。 回T退订.";
////		String str1 = "您的手机验证码为：_，请在5分钟内完有效。如非本人操作请忽略本短信。回T退订.";
//		List<Object> list = new ArrayList<Object>();
//		list.add("account");
//		list.add("year");
//		list.add("month");
//		list.add("day");
//		list.add(874198);
//		System.out.println(generateString(str, list));
//	}
}


